package com.ruoyi.tester.executor.expression;

import com.ruoyi.tester.executor.ExpressionContext;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

/**
 * @author SongJun
 * @description TODO:
 * @date 2021/7/8 9:02
 */
//@Component
//替换为ExpAt
public class ExpJSONArray implements ExpressionAnalysis {
    @Override
    public String getExpressionName() {
        return "JSONArrayValue";
    }

    @Override
    public String getDescription() {
        return "中括号括起来的数字, 如: [0], 表示从当前json数组类型的上下文中获取对应下标的值;";
    }

    @Override
    public Object analysis(ExpressionContext context, String... param) {
        ExpJSONObject.ExpJSONResult rst = new ExpJSONObject.ExpJSONResult();
        int close = param[0].indexOf("]");
        String index = param[0].substring(1, close);
        JSONArray node;
        if(context.getContext() instanceof JSONArray){
            node = (JSONArray) context.getContext();
        } else if(context.getContext() instanceof String){
            node = new JSONArray((String)context.getContext());
        } else {
            node = new JSONArray(context.getContext());
        }
        if (node != null || node.length() > Integer.valueOf(index)) {
            int pos;
            if(index.startsWith("-")){
                pos = Integer.valueOf(index) + node.length() - 1;
            } else {
                pos = Integer.valueOf(index);
            }
            if(pos > node.length() - 1 || pos < 0){
                int questionMark = param[0].indexOf("?");
                if(questionMark > 0){
                    rst.setValue(param[0].substring(questionMark +1));
                    rst.setContinuous(false);
                    return rst;
                } else {
                    throw new RuntimeException("解析"+param[1]+"中"+param[0]+"数据异常");
                }
            }
            if (node.get(pos) instanceof JSONArray) {
                rst.setValue(node.getJSONArray(pos));
            } else if (node.get(pos) instanceof JSONObject) {
                rst.setValue(node.getJSONObject(pos));
            } else if (node.get(pos) instanceof String) {
                rst.setValue(node.getString(pos));
            } else if (node.get(pos) instanceof Long) {
                rst.setValue(node.getLong(pos));
            } else if (node.get(pos) instanceof Integer) {
                rst.setValue(node.getInt(pos));
            }
        } else {
            throw new RuntimeException("依赖参数返回异常"+param[1]);
        }
        return rst;
    }
}
